package com.dandelion.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dandelion.business.entity.SysRoleMenu;
import com.dandelion.business.entity.SysUserRole;
import com.dandelion.business.entity.vo.user.req.BindRoleReqVO;
import com.dandelion.business.mapper.SysUserRoleMapper;
import com.dandelion.business.service.ISysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dandelion.framework.common.R;
import com.dandelion.framework.enums.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Set;

/**
 * 系统用户角色服务impl
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 宋发准
 * @date 2021/12/29
 * @since 2021-12-26
 */
@Service
@Slf4j
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    /**
     * 绑定角色
     *
     * @param req 要求事情
     * @return {@link R}<{@link Boolean}>
     */
    @Override
    public R<Boolean> bindRole(BindRoleReqVO req) {
        Long uid = req.getUid();
        //清除旧数据
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, uid);
        remove(wrapper);

        //保存新数据
        Set<Long> rids = req.getRids();
        ArrayList<SysUserRole> roles = new ArrayList<>();
        for (Long rid : rids) {
            SysUserRole role = new SysUserRole();
            role.setUserId(uid);
            role.setRoleId(rid);
            roles.add(role);
        }
        boolean batch = false;
        try {
            batch = saveBatch(roles);
            if (batch) {
                return R.ok().data(true);
            }
        } catch (Exception e) {
            log.warn("用户绑定角色异常:{}", e.getMessage());
        }
        return R.fail(CodeEnum.USER_BIND_ROLE_ERROR).data(batch);
    }
}
